package servlet.login;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import bean.Admin;
import dao.AdminDAO;

/**
 * Servlet implementation class Demo
 */
@WebServlet("/Login")
public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Login() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 *      
	 *      登录判断
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		
		AdminDAO adminDAO = new AdminDAO();
		String account = request.getParameter("u");
		String pwd = request.getParameter("p");
		Admin admin = adminDAO.getAdmin(account);
		if ((admin != null) && (admin.getPwd().trim().equals(pwd))) {
			Cookie cookie = new Cookie("login", "true");
			cookie.setMaxAge(-1);
			response.addCookie(cookie);
			request.getSession().setAttribute("admin", admin);
			response.sendRedirect("./jsp/manage/manageNews.jsp");
		} else {
			request.getSession().setAttribute("loginSuccess", "fail");
			response.sendRedirect("./jsp/login.jsp");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
